import React, { useState } from 'react';
import { Button, message, Modal, Steps } from 'antd';
import { LockOutlined, MobileOutlined } from '@ant-design/icons';
import { ProForm, ProFormCaptcha, ProFormText } from '@ant-design/pro-components';
import { SmsCodes, SmsOperation } from '@/constants/SmsConstants';
import {forgetPasswordAPI, getFakeCaptcha, verifyCodeAPI} from "@/services/auth";

const { Step } = Steps;

const ForgotPasswordModal: React.FC = () => {
  const [visible, setVisible] = useState(false);
  const [currentStep, setCurrentStep] = useState(0);
  const [form] = ProForm.useForm();
  const [loading, setLoading] = useState<boolean>(false)
  const [token, setToken] = useState<string>('')
  const [phone, setPhone] = useState<string>('')

  const handleVerifyCode = async () => {
    setLoading(true)
    const {code, phone} = await form.validateFields(['phone', 'code'])
    if (!code || !phone) {
      message.error('手机号或验证码不能为空')
      setLoading(false)
      return
    }
    const {data} = await verifyCodeAPI(phone, code, SmsOperation.FORGET_PASSWORD)
    if (!data) {
      message.error('验证码错误')
      setLoading(false)
      return
    }
    setToken(data.token)
    setCurrentStep(1)
    message.success('验证码验证成功')
    setPhone(phone)
    setLoading(false)
  };

  const handleResetPassword = async () => {
    setLoading(true)
    const {newPassword, confirmPassword} = await form.validateFields(['newPassword', 'confirmPassword'])
    if (!newPassword || !confirmPassword) {
      message.error('密码不能为空')
      setLoading(false)
      return
    }
    if (newPassword !== confirmPassword) {
      message.error('两次输入的密码不一致')
      setLoading(false)
      return
    }
    const {data} = await forgetPasswordAPI(phone, token, newPassword)
    if (!data) {
      message.error('重置密码失败')
    }
    setVisible(false)
    message.success('重置密码成功')
    setCurrentStep(0)
    form.resetFields()
    setLoading(false)
  };

  const steps = [
    {
      title: '验证手机号',
      content: (
        <ProForm
          form={form}
          submitter={false}
          layout="vertical"
        >
          <ProFormText
            name="phone"
            label="手机号"
            fieldProps={{
              size: 'large',
              prefix: <MobileOutlined/>,
            }}
            placeholder="请输入手机号"
            rules={[
              {required: true, message: '请输入手机号'},
              {pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号'},
            ]}
          />
          <ProFormCaptcha
            fieldProps={{
              size: 'large',
              prefix: <MobileOutlined/>,
            }}
            captchaProps={{
              size: 'large',
            }}
            placeholder="请输入验证码"
            captchaTextRender={(timing, count) => {
              if (timing) {
                return `${count} 秒后重新获取`;
              }
              return '获取验证码';
            }}
            name="code"
            phoneName={'phone'}
            rules={[
              {
                required: true,
                message: '请输入验证码',
              },
            ]}
            onGetCaptcha={async (phone) => {
              if (!phone) {
                message.error('请输入手机号！');
                throw new Error('请输入手机号！')
              }
              const {data} = await getFakeCaptcha(phone, SmsCodes.FORGET_PASSWORD);
              if (!!data) {
                message.success('验证码发送成功！');
              }
            }}
          />
        </ProForm>
      ),
    },
    {
      title: '设置新密码',
      content: (
        <ProForm
          form={form}
          submitter={false}
          layout="vertical"
        >
          <ProFormText.Password
            name="newPassword"
            label="新密码"
            fieldProps={{
              size: 'large',
              prefix: <LockOutlined/>,
            }}
            placeholder="请输入新密码"
            rules={[
              {required: true, message: '请输入新密码'},
              {min: 6, message: '密码长度不能少于6位'},
            ]}
          />
          <ProFormText.Password
            name="confirmPassword"
            label="确认密码"
            fieldProps={{
              size: 'large',
              prefix: <LockOutlined/>,
            }}
            placeholder="请再次输入新密码"
            dependencies={['newPassword']}
            rules={[
              {required: true, message: '请确认新密码'},
              ({getFieldValue}) => ({
                validator(_, value) {
                  if (!value || getFieldValue('newPassword') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致'));
                },
              }),
            ]}
          />
        </ProForm>
      ),
    },
  ];

  return (
    <>
      <Button type="link" onClick={() => setVisible(true)}>
        忘记密码?
      </Button>
      <Modal
        title="找回密码"
        open={visible}
        onCancel={() => {
          setVisible(false);
          setCurrentStep(0);
          form.resetFields();
        }}
        footer={[
          currentStep > 0 && (
            <Button key="back" onClick={() => setCurrentStep(currentStep - 1)}>
              上一步
            </Button>
          ),
          currentStep < steps.length - 1 ? (
            <Button
              key="next"
              type="primary"
              loading={loading as any}
              onClick={handleVerifyCode}
            >
              下一步
            </Button>
          ) : (
            <Button
              key="submit"
              type="primary"
              loading={loading}
              onClick={handleResetPassword}
            >
              提交
            </Button>
          ),
        ]}
      >
        <Steps current={currentStep} style={{marginBottom: 24}}>
          {steps.map((item) => (
            <Step key={item.title} title={item.title}/>
          ))}
        </Steps>
        <div>{steps[currentStep].content}</div>
      </Modal>
    </>
  );
};

export default ForgotPasswordModal;
